import React, {
    Component,
} from 'react';
import {
    StyleSheet,
    Text,
    View,
    Platform,
    Dimensions,
    TouchableOpacity,
    Alert,
    FlatList,
    TextInput,
    Linking,
    Image,
    DeviceEventEmitter,
    ScrollView
} from 'react-native';

import moment from 'moment';
import HttpUtils from '../../utils/HttpUtils';
import HttpUrls from '../../utils/HttpUrls';
import AndroidModule from "../../utils/AndroidConnent";
import { ToastToUser } from "../../utils/CustomToast";
import Constant from '../../utils/Constant'
import NoData from '../../utils/NoData'
import Loading from "../../utils/Loading";
import { getImgUrl } from '../../utils/ComFunction'
import Header from "../../components/header";
import Picker from 'react-native-picker'
import ImageCropPicker from 'react-native-image-crop-picker';
import Upload from '../../components/upload/Upload'

const screenW = Dimensions.get('window').width;

let initialPage
let navigation
/**
 * 上传支付凭证
 */
export default class UploadPayInfoPage extends Component {
    constructor(props) {
        super(props);
        this.state = {
            payEvidence: '',
            payType: '',
            paymentMethod: '',//1:电汇， 2:支付宝， 3:微信)
            from: this.props.route.params.from,//1 预付款 2尾款
            orderNo: this.props.route.params.orderNo,
            receiveId: this.props.route.params.receiveId,//收款方账户id
        }
    }

    componentDidMount() {

    }

    render() {
        navigation = this.props.navigation;
        return (
            <View style={styles.container}>
                <Header navigation={navigation} hideSepLine={true} Title={'凭证上传'} ></Header>

                <View style={styles.uploadContain}>
                    <Text style={styles.uploadTipTitleText}>请上传付款凭证<Text style={{ color: '#ED542E' }}>*</Text></Text>

                    {this.state.payEvidence != '' ?
                        <View style={{ width: 85 }}>
                            <Image style={styles.uploadImg} source={{ uri: getImgUrl(this.state.payEvidence) }} />

                            <TouchableOpacity
                                onPress={() => {
                                    this.setState({
                                        payEvidence: ''
                                    })
                                }}
                                style={{ position: 'absolute', right: 0, top: 5, width: 30, height: 30 }}>
                                <Image style={{ width: 18, height: 18, marginLeft: 12 }} source={require('source/image/delete_car_icon.png')} />
                            </TouchableOpacity>
                        </View>

                        :
                        <TouchableOpacity
                            onPress={() => {
                                this.uploadPayImg()
                            }}>
                            <Image style={styles.uploadImg} source={require('source/image/add_img_icon.png')} />
                        </TouchableOpacity>
                    }
                </View>

                <TouchableOpacity
                    style={styles.payTypeContain}
                    onPress={() => {
                        this.showTypePicker()
                    }}>

                    <Text style={styles.typeTitle}>支付方式</Text>

                    <View style={{ flexDirection: 'row', alignItems: 'center' }}>
                        <Text style={[styles.typeText, { color: this.state.payType == '' ? '#999999' : '#333333' }]}>{this.state.payType == '' ? '请选择支付方式' : this.state.payType}</Text>
                        <Image style={styles.arrowImg} source={require('source/image/comm/icon_tree_arrow.png')} />
                    </View>

                </TouchableOpacity>


                <View style={styles.bottomContain}>
                    <TouchableOpacity
                        style={styles.bottomButton}
                        onPress={() => {
                            this.submitPayInfo()
                        }}>
                        <Text style={styles.bottomButtonText}>提交</Text>
                    </TouchableOpacity>
                </View>


                <Loading onRef={(ref) => (this.Loading = ref)} loadingText={'上传中...'} />

            </View>
        )
    }

    showTypePicker() {
        let data = [
            '电汇',
            '支付宝',
            '微信',
        ];
        Picker.init({
            pickerData: data,
            selectedValue: [],
            // pickerBg:[255, 0 ,0, 1],
            pickerFontColor: [0, 0, 0, 1],
            pickerCancelBtnText: '取消',
            pickerCancelBtnColor: [134, 136, 137, 1],
            pickerConfirmBtnText: '确认',
            pickerTitleText: '',
            pickerToolBarBg: [255, 255, 255, 1],
            pickerBg: [255, 255, 255, 1],

            onPickerConfirm: data => {
                console.log(data)
                let value = data[0];
                let typeValue = 0
                if (value == '电汇') {
                    typeValue = 1
                } else if (value == '支付宝') {
                    typeValue = 2
                } else if (value == '微信') {
                    typeValue = 3
                }
                
                
                this.setState({
                    payType: data[0],
                    paymentMethod: typeValue
                })
            },
            onPickerCancel: data => {

            },
            onPickerSelect: data => {

            }
        });
        Picker.show();
    }

    submitPayInfo(){
        if (this.state.payEvidence == '') {
            
            ToastToUser('请上传支付凭证');
            return;
        }
        if (this.state.payType == '') {
            ToastToUser('请选择支付方式');
            
            return;
        }
        if(this.Loading){
            this.Loading.show();
        }
        if(this.state.from == 1){
            this.advancePaymentReceipt();
        }else if(this.state.from == 2){
            this.tailPaymentReceipt();

        }else{
            this.afterSaleUploadReceipt()
        }
    }

    uploadPayImg() {
        const option = { mediaType: "photo", cropping: false, multiple: false, compressImageMaxWidth: 1024, compressImageMaxHeight: 1024 };
        ImageCropPicker.openPicker(option).then(images => {
            if (this.Loading) {
                this.Loading.show();
            }
            Upload.getAlipz(images.path, Upload.OSS_CONTRACT, this.uploadafterfun);//获取阿里凭证。

        }, (error) => {
            // alert(error);
        });
    }

    uploadafterfun = (bojkey) => {
        if (this.Loading) {
            this.Loading.hide();
        }
        this.setState({
            payEvidence: bojkey
        })
    }

    /**
     * 支付预付款
     */
    advancePaymentReceipt() {
        let param = {
            orderNo: this.state.orderNo,
            paymentVoucher: this.state.payEvidence,
            receiveId: this.state.receiveId,
            paymentMethod: this.state.paymentMethod,
        }


        HttpUtils.postRequest(HttpUrls.advancePaymentReceipt, param)
            .then((result) => {
                if (this.Loading) {
                    this.Loading.hide();
                }
                if (result.code == 0) {
                    ToastToUser('上传预付款凭证成功')
                    DeviceEventEmitter.emit('refreshOrderDetail', {})
                    if (this.props.route.params.uploadPayInfoSuccess) {
                        this.props.route.params.uploadPayInfoSuccess();
                    }
                    navigation.goBack()
                }else{
                    ToastToUser(result.msg+'')
                }
            })
            .catch((error) => {

            })

    }

    /**
     * 买家支付30%尾款上传回执
     */
    tailPaymentReceipt() {
        let param = {
            orderNo: this.state.orderNo,
            paymentVoucher: this.state.payEvidence,
            receiveId: this.state.receiveId,
            paymentMethod: this.state.paymentMethod,
        }


        HttpUtils.postRequest(HttpUrls.tailPaymentReceipt, param)
            .then((result) => {
                if (this.Loading) {
                    this.Loading.hide();
                }
                if (result.code == 0) {
                    ToastToUser('上传尾款凭证成功')
                    DeviceEventEmitter.emit('refreshOrderDetail', {})
                    navigation.goBack()
                }else{
                    ToastToUser(result.msg+'')
                }
            })
            .catch((error) => {

            })

    }

    /**
     * 售后付款
     */
     afterSaleUploadReceipt() {
        let param = {
            orderNo: this.state.orderNo,
            paymentVoucher: this.state.payEvidence,
            receiveId: this.state.receiveId,
            paymentMethod: this.state.paymentMethod,
        }


        HttpUtils.postRequest(HttpUrls.afterSaleUploadReceipt, param)
            .then((result) => {
                if (this.Loading) {
                    this.Loading.hide();
                }
                if (result.code == 0) {
                    ToastToUser('上传付款凭证成功')
                    DeviceEventEmitter.emit('refreshAfterOrderDetail', {})
                    if (this.props.route.params.uploadPayInfoSuccess) {
                        this.props.route.params.uploadPayInfoSuccess();
                    }
                    navigation.goBack()
                }else{
                    ToastToUser(result.msg+'')
                }
            })
            .catch((error) => {

            })

    }



}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: '#F9F9F9',
    },

    arrowImg: {
        width: 16,
        height: 16
    },

    uploadContain: {
        marginLeft: 16,
        marginRight: 16,
        marginTop: 16,
        marginBottom: 16,
        backgroundColor: '#fff',
        borderRadius: 4,
        padding: 16
    },

    uploadTipTitleText: {
        fontSize: 16,
        color: '#222222',
        fontWeight: '500'
    },

    uploadImg: {
        width: 75,
        height: 75,
        marginTop: 16,

        marginRight: 16,
        borderRadius: 4
    },

    payTypeContain: {
        flexDirection: 'row',
        alignItems: 'center',
        justifyContent: 'space-between',
        backgroundColor: '#fff',
        marginLeft: 16,
        marginRight: 16,
        height: 46,
        borderRadius: 4,
        paddingHorizontal: 16
    },
    typeTitle: {
        fontSize: 14,
        color: '#333333',
        fontWeight: '500'
    },
    typeText: {
        fontSize: 14,
        color: '#999999',

    },

    bottomContain: {
        position: 'absolute',
        bottom: 0,
        left: 0,
        width: '100%',
        height: 100,
        flexDirection: 'row',
        
        backgroundColor: '#fff',
    },
    bottomButton: {
        margin:15,
        height: 46,
        alignItems: 'center',
        justifyContent: 'center',
        backgroundColor: '#FFE000',
        flex: 1,
        borderRadius:46
    },
    bottomButtonText: {
        fontSize: 16,
        color: '#333',
        fontWeight: '500'
    },

})